package com.konsung.ksdc.common.network;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Response;

/**
 * Created by wanghantao on 2017/1/12.
 */
public abstract class MyFileCallBack extends Callback<File> {
    private String destFileDir;
    private String destFileName;
    private boolean flag = true;

    /**
     * 设置标记
     * @param flag 标记
     */
    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    /**
     * 构造方法
     * @param destFileDir 文件夹路径
     * @param destFileName 文件名称
     */
    public MyFileCallBack(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }

    /**
     * 进度条
     * @param var1 浮点参数1
     * @param var2 长度
     */
    public abstract void inProgress(float var1, long var2);

    @Override
    public File parseNetworkResponse(Response response) throws Exception {
        return saveFile(response);
    }

   /* @Override
    public void onError(Call call, Exception e) {

    }

    @Override
    public void onResponse(File file) {

    }*/

    /**
     * 保存文件
     * @param response 响应数据
     * @return 文件
     * @throws IOException 异常
     */
    public File saveFile(Response response) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        boolean len = false;
        FileOutputStream fos = null;

        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0l;
            File dir = new File(this.destFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File file = new File(dir, this.destFileName);
            fos = new FileOutputStream(file);

            int len1;
            while ((len1 = is.read(buf)) != -1 && flag) {
                sum += (long) len1;
                fos.write(buf, 0, len1);
                final long finalSum1 = sum;
                OkHttpUtils.getInstance().getDelivery().post(new Runnable() {
                    public void run() {
                        MyFileCallBack.this.inProgress((float) finalSum1 * 1.0F / (float) total,
                                total);
                    }
                });
            }

            fos.flush();
            File finalSum = file;
            return finalSum;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException var22) {

            }

            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException var21) {

            }
        }
    }
}
